import { SdkRewardVideoState } from "../SdkConstants"
import SdkUtil from "../SdkUtil"
import SdkBase from "./SdkBase"


enum RecordState { Free, Recording, Pause }


export default class SdkWechat extends SdkBase {
    private env: IWechat

    private rewardVideo: IWechatRewardVideo

    private recorder: any

    private _recordTimer: number
    private _recordState: RecordState = RecordState.Free
    private _recordTime: number = 0
    private _recordOver = false


    public constructor(shareCallBack?: Function) {
        super()

        this.env = window['wx']

        // 设置右上角点开的详情界面中的分享按钮是否可用
        // withShareTicket 是否使用带 shareTicket 的转发
        // shareAppMessage 表示“发送给朋友”按钮，"shareTimeline"表示“分享到朋友圈”按钮
        this.env['showShareMenu']({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })

        if (shareCallBack) {
            this.env['onShareAppMessage'](shareCallBack)
        }

        this.recorder = this.env['getGameRecorder']()
    }


    public getLaunchOptionsSync(): Object {
        return this.env['getLaunchOptionsSync']()
    }

    public share(title?: string, imageUrl?: string, imageUrlId?: string, query?: string) {
        const params = {}

        title && (params['title'] = title)
        imageUrl && (params['imageUrl'] = imageUrl)
        imageUrlId && (params['imageUrlId'] = imageUrlId)
        query && (params['query'] = query)

        this.env['shareAppMessage'](params)
    }


    public rewardVideoPlay(id: string, cb: (state: number, ret?: any) => void) {
        if (!this.rewardVideo) {
            this.rewardVideo = this.env.createRewardedVideoAd({ adUnitId: id })
            if (!this.rewardVideo) {
                cb(SdkRewardVideoState.PlayError, 'createRewardedVideoAd 失败')
                return
            }
        }


        const closeCall = (ret: IWechatRewardVideoCloseRet) => {
            if (!ret || ret.isEnded) {
                cb(SdkRewardVideoState.CloseReward)
            } else {
                cb(SdkRewardVideoState.Close)
            }

            this.rewardVideo.offClose(closeCall)
            this.rewardVideo.offError(errorCall)
        }

        const errorCall = (err: any) => {
            cb(SdkRewardVideoState.PlayError, 'err:' + JSON.stringify(err))

            this.rewardVideo.offClose(closeCall)
            this.rewardVideo.offError(errorCall)
        }


        this.rewardVideo.onClose(closeCall)
        this.rewardVideo.onError(errorCall)

        this.rewardVideo.load().then(() => {
            this.rewardVideo.show().
                then(() => cb(SdkRewardVideoState.PlaySuccess)).
                catch(err => console.error('wechat rewardVideo show catch err:' + JSON.stringify(err)))
        }).catch(err => {
            console.error('wechat rewardVideo load catch err:' + JSON.stringify(err))
        })
    }


    public get recordIsSupport(): boolean {
        return this.recorder.isFrameSupported()
    }

    public recordStart(duration: number, stopCb?: Function) {
        if (this._recordState != RecordState.Free) return

        this._recordState = RecordState.Recording
        this._recordOver = false

        const onStart = () => {
            this._recordTime = SdkUtil.unixtime()
            console.error(`Wechat 录屏开始 duration:${duration},recordTime:${this._recordTime}`)

            // 真正开始录制后的 5 秒后结束录制
            this._recordTimer = setTimeout(() => {
                this.recorder.stop()
            }, duration * 1000)
        }

        const onStop = () => {
            this._recordState = RecordState.Free
            this._recordTime = SdkUtil.unixtime() - this._recordTime
            this._recordOver = true

            console.error(`Wechat 录屏完成 unixtime:${SdkUtil.unixtime()},recordTime:${this._recordTime}`)

            stopCb && stopCb()

            this.recorder.off('start', onStart)
            this.recorder.off('stop', onStop)
        }

        this.recorder.start()

        this.recorder.on('start', onStart)
        this.recorder.on('stop', onStop)
    }

    public recordStop() {
        if (this._recordState != RecordState.Recording && this._recordState != RecordState.Pause) return

        clearTimeout(this._recordTimer)

        this.recorder?.stop()
    }

    public recordPause() {
        if (this._recordState != RecordState.Recording) return

        this._recordState = RecordState.Pause
        this.recorder?.pause()
    }

    public recordResume() {
        if (this._recordState != RecordState.Pause) return

        this._recordState = RecordState.Recording
        this.recorder?.resume()
    }

    public recordShare(needTime: number, param?: Object): string {
        if (!this._recordOver) return '录屏失败：录屏未结束'
        if (this._recordTime < needTime) return `录屏失败：录屏时长低于 ${needTime} 秒`

        console.error('recordShare 111:', this.env['operateGameRecorderVideo'])
        this.env['operateGameRecorderVideo'](param)
        console.error('recordShare 222')

        return null
    }


    /**
     * 使手机发生较短时间的振动（15 ms）
     * @param type 震动强度类型，有效值为：heavy、medium、light
     */
    public vibrateShort(type: string) {
        if (!this.env['vibrateShort']) return

        this.env['vibrateShort']({ type })
    }

    public vibrateLong() {
        if (!this.env['vibrateLong']) return

        this.env['vibrateLong']()
    }
}
